<template>
  <div class="arrival-container">
    <!--搜索框-->
    <!-- 搜索框：筛选条件与后端返回字段严格对齐 -->
    <el-form :inline="true" :model="filters" class="search-form" label-width="100px">
      <el-form-item label="到货登记号：">
        <el-input 
          v-model="filters.arrivalCode" 
          clearable 
          style="width: 200px;"
        />
      </el-form-item>
      <el-form-item label="采购单号：">
        <el-input 
          clearable 
          v-model="filters.purchaseCode" 
          style="width: 200px;"
        />
      </el-form-item>

      <el-form-item label="供应商：">
        <el-input 
          clearable
          v-model="filters.supplier"  
          style="width: 200px;"
        />
      </el-form-item>

      <el-form-item label="采购日期：">
        <el-date-picker
          type="date"
          v-model="filters.pBeginDate"
          clearable
          placeholder="起始日期"
          style="margin-right: 10px;"
        />
        <el-date-picker
          type="date"
          v-model="filters.pEndDate"
          placeholder="截止日期"
          clearable
        />
      </el-form-item>

      <el-form-item label="产品品类：">
        <el-input 
          clearable
          v-model="filters.category" 
          style="width: 200px;"
        />
      </el-form-item>

      <el-form-item label="采购人：">
        <el-input 
          clearable
          v-model="filters.purchaseUser" 
          style="width: 200px;"
        />
      </el-form-item>

      <el-form-item label="产品类型：">
        <el-select 
          clearable 
          v-model="filters.productType"
          style="width: 200px;"
        >
          <el-option label="原料" value="1"></el-option>
          <el-option label="半成品" value="2"></el-option>
          <el-option label="成品" value="3"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="到货日期：">
        <el-date-picker
          type="date"
          v-model="filters.aBeginDate"
          clearable
          placeholder="起始日期"
          style="margin-right: 10px;"
        />
        <el-date-picker
          type="date"
          v-model="filters.aEndDate"
          placeholder="截止日期"
          clearable
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="conditionQuery">查询</el-button>
        <el-button style="margin-left: 10px;" @click="resetFilters">重置</el-button>
      </el-form-item>
    </el-form>
    <!--表格数据-->
    <el-table :data="tableData" style="width: 100%" stripe border>
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="arrivalCode" label="到货登记号" />
      <el-table-column prop="purchaseCode" label="采购单号" />
      <el-table-column prop="supplier" label="供应商名称"/>
      <el-table-column prop="category" label="产品品类" />
      <el-table-column prop="productType" label="产品类型">
        <template v-slot="{row}">
          {{goodMap[row.productType]}}
        </template>
      </el-table-column>
      <el-table-column prop="purchaseDate" label="采购日期" />
      <el-table-column prop="purchaseUser" label="采购人" />
      <el-table-column prop="arrivalDate" label="到货日期"  />
      <el-table-column prop="addType" label="添加类型" >
        <template v-slot="{row}">
          {{addMap[row.addType]}}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" text-align="center">
        <template v-slot="{ row }">
          <el-button type="primary" @click="toDetail(row.id)">到货详情</el-button>
          <el-button type="success" @click="toInspect(row.id)">到货质检</el-button>
          <el-button type="danger" @click="todel(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <el-pagination 
      background 
      layout="sizes,total,prev,pager,next,jumper" 
      :total="total" 
      class="pagination" 
      :page-size="pageSize"
      :current-page="page"
      :page-sizes="[5, 10, 20]"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
    />
  </div>
</template>

<script setup>
  import {ref,onMounted} from "vue"
  import {getList,deleteArrivalById} from "@/api/arrival/arrival.js"
  import {useRouter} from 'vue-router';
  import { ElMessage,ElMessageBox } from 'element-plus'
  //响应式对象
  const tableData=ref([]);
  const total = ref(0);      // 总记录数
  const page = ref(1);       // 当前页
  const pageSize = ref(5);   // 每页条数
  //获取路由实例
  const router=useRouter();
  //筛选条件
  const filters=ref({
    purchaseCode:undefined,
    purchaseDate:undefined,
    supplier:undefined,
    purchaseUser:undefined,
    category:undefined,
    productType:undefined,
    arrivalCode:undefined,
    arrivalDate:undefined,
    pBeginDate:undefined,
    pEndDate:undefined,
    aBeginDate:undefined,
    aEndDate:undefined
  });
  //添加类型
  const addMap={
    1: '标准流程',
    2: '快捷流程'
  }
  //产品品类
  const goodMap={
    1: '原料',
    2: '半成品',
    3: '成品'
  }

   //跳转详情
  function toDetail(id){
    router.push({path:"/arrival/arrivalDetail",query:{id}});
  }
  //跳转到质检信息
  function toInspect(id){
    router.push({path:"/arrival/qualityInspection",query:{id}})
  }

// 删除 - 修复后代码
function todel(row) {
  ElMessageBox.confirm(
    '确定要删除这条数据吗？此操作不可撤销',
    '删除确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  .then(async () => {
    try {
      const res = await deleteArrivalById(row.id);
      if (res.code === 200) {
        ElMessage({ type: 'success', message: '删除成功' });
        init(); 
      } else {
        ElMessage({ 
          type: 'error', 
          message: res.msg || '删除失败，请重试' 
        });
      }
    } catch (err) {
      ElMessage({ 
        type: 'error', 
        message: '接口请求失败，请检查网络或联系开发人员' 
      });
    }
  })
  .catch((err) => {
    // 4. 仅当用户主动取消时，才提示“已取消删除”
    if (err.name === 'Canceled') {
      ElMessage({ type: 'info', message: '已取消删除' });
    }
    
  });
}

// 工具函数：日期格式化（后端需要YYYY-MM-DD字符串，与返回的purchaseDate格式一致）
const formatDate = (date) => {
  if (!date) return undefined; // 无日期时不传递该参数，避免后端条件干扰
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 补0（如7→07）
  const day = String(date.getDate()).padStart(2, '0');        // 补0（如8→08）
  return `${year}-${month}-${day}`;
};

  //定义请求方法
  async function init(){

    const params={
      page: page.value,
      pageSize: pageSize.value,
      //筛选条件
      ...(filters.value.arrivalCode && {arrivalCode: filters.value.arrivalCode }),
      ...(filters.value.purchaseCode && { purchaseCode: filters.value.purchaseCode }),
      ...(filters.value.supplier && { supplier: filters.value.supplier }), // 关键：传递supplier而非supplierName
      //采购日期
      ...(filters.value.pBeginDate && { pBeginDate: formatDate(filters.value.pBeginDate) }),
      ...(filters.value.pEndDate && { pEndDate: formatDate(filters.value.pEndDate) }),
      ...(filters.value.category && { category: filters.value.category }),
      ...(filters.value.purchaseUser && { purchaseUser: filters.value.purchaseUser }),
      ...(filters.value.productType !== undefined && { productType: filters.value.productType }),
      //到货日期
      ...(filters.value.aBeginDate && { aBeginDate: formatDate(filters.value.aBeginDate) }),
      ...(filters.value.aEndDate && { aEndDate: formatDate(filters.value.aEndDate) })
    };
    try {
      const res = await getList(params);
      if (res.code === 200) {
        tableData.value = res.data.list; 
        total.value = res.data.total;

      }
    } catch (error) {
      ElMessage.error('接口请求异常，请检查网络或后端服务');
      console.error('请求错误详情：', error);
    }
  }

  //分页
  const handlePageChange = (newPage) => {
    page.value = newPage;
    init(); // 重新请求当前页数据
  };
  // 每页条数改变
  const handleSizeChange = (newSize) => {
    pageSize.value = newSize;
    page.value = 1; // 条数改变时重置为第1页
    init();
  };
  //查询
  const conditionQuery = () => {
    page.value = 1; // 筛选条件改变时，从第1页开始查询
    init();
  };
  //重置
  const resetFilters = () => {
    Object.keys(filters.value).forEach(key => {
      filters.value[key] = undefined;
    });
    page.value = 1; // 重置为第1页
    init(); // 重新请求全部数据
  };

  //页面渲染后调用
  onMounted(()=>{
    init();
  })

</script>

<style scoped>
.arrival-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

</style>